package com.mxx.common.generator.convert;

import com.mxx.common.generator.*;
import com.mxx.common.generator.db.Table;
import com.mxx.common.generator.db.TableColumn;

public class DefaultTableToEntityInfo implements TableToEntityInfo {

    private GlobalNameConfig globalNameConfig;
    private NameConverter nameConverter;
    private TypeConvertHandler typeConvertHandler;

    public DefaultTableToEntityInfo(GlobalNameConfig globalNameConfig, NameConverter nameConverter, TypeConvertHandler typeConvertHandler) {
        this.globalNameConfig = globalNameConfig;
        this.nameConverter = nameConverter;
        this.typeConvertHandler = typeConvertHandler;
    }

    @Override
    public EntityInfo toEntity(Table table) {
        String entityName = nameConverter.tableNameToEntityName(table.getTableName());

        EntityInfo entityInfo = new EntityInfo(Constant.EntityType.CLASS);
        entityInfo.setTable(table)
                .setEntityName(entityName)
                .setRemark(table.getRemark())
                .setEntityPackage(globalNameConfig.getEntityPackage())
                .setEntityVisible(Constant.EntityVisible.PUBLIC)
                .flushEntityClass();
        for (TableColumn tableColumn : table.getTableColumnList()) {
            String fieldName = nameConverter.tableFieldToEntityField(tableColumn.getColumnName());
            EntityField entityField = new EntityField()
                    .setTableColumn(tableColumn)
                    .setFieldName(fieldName)
                    .setRemark(tableColumn.getRemark())
                    .setMysqlType(tableColumn.getMysqlType());

            typeConvertHandler.convert(entityField);
            entityInfo.addEntityField(entityField);
        }
        return entityInfo;
    }

}
